<?php

class SingleMail_Controller Extends Controller {

	private $inc;
	private $platformlist;
    private $type_object;
	private $keeptimelist;	//保存时间
	private $areaList;	//区号列表
	private $tmpConn;
	
    function _init() {
        check_level(50, segment(0), segment(1, 'index'));
		//var_dump($this->db);
        $this->areaList = get_area_list_host();
        $this->type_object = get_type_object_db();
        $this->keeptimelist = array(
        		'1'=>'1',
        		'3'=>'3',
        		'7'=>'7',
        		'30'=>'30',
        );
        //var_dump($this->db);
       $this->db->select_db();
       
       $this->inc = $this->config['inc'];
       $this->platformlist = $this->inc['platform_list'];
    }

    function index() {
        $this->view->display("mail/singlemail/index");
    }

    function flexigrid() {
        //读取flexigrid传输的数据
        list($colkey, $colsinfo, $where, $sortname, $sortorder, $offset, $rp, $page) = $this->common->get_flexigrid_params();
		//echo " before ";
        //print_r($this->db);
        //$this->load->database('db');
        //echo " after ";
        //var_dump($this->db);
        //echo $this->db->connectDetail();
        
        $rows = array();
        $where = $where . " and type=0 ";
        $sql = "SELECT COUNT(autoid) AS num FROM mail_message WHERE {$where}";
        //var_dump($this->db);
        
        //print_r($this->db);
        $one = $this->db->one($sql);
        //print_r($this->db);
        //var_dump($this->db);
        $total = $one['num'];
        $orderby = $sortname ? "ORDER BY {$sortname} {$sortorder} " : "ORDER BY autoid DESC";
        $sql = "SELECT {$colsinfo} FROM mail_message WHERE {$where} {$orderby} LIMIT {$offset},{$rp}";
        $this->db->query($sql);
        //print_r($this->db);
        
        
        while ($n = $this->db->get_array('default')) {
            $n['itemid1'] = $n['itemid1'] == '' ? '' : $this->type_object[substr($n['itemid1'], 0, strpos($n['itemid1'], ','))] . ':' . substr($n['itemid1'], strpos($n['itemid1'], ',') + 1);
            $n['itemid2'] = $n['itemid2'] == '' ? '' : $this->type_object[substr($n['itemid2'], 0, strpos($n['itemid2'], ','))] . ':' . substr($n['itemid2'], strpos($n['itemid2'], ',') + 1);
            $n['itemid3'] = $n['itemid3'] == '' ? '' : $this->type_object[substr($n['itemid3'], 0, strpos($n['itemid3'], ','))] . ':' . substr($n['itemid3'], strpos($n['itemid3'], ',') + 1);
            $n['itemid4'] = $n['itemid4'] == '' ? '' : $this->type_object[substr($n['itemid4'], 0, strpos($n['itemid4'], ','))] . ':' . substr($n['itemid4'], strpos($n['itemid4'], ',') + 1);
            $n['area_host'] = $this->areaList[$n['area_host']];
            $n['platform'] = $this->platformlist[$n['platform']];
            //$n['insert_time'] = get_datetime($n['insert_time']);
            $rows[] = array('id' => $n['autoid'], 'cell' => ($n));
        }
        $result = array(
            'page' => $page,
            'total' => $total,
            'rows' => $rows
        );
        echo json_encode($result);
    }

    function add() {
        set_time_limit(0);
        
        if (is_submit()) {
            $rowdata = $_POST['row'];
            //print_r($rowdata);
            //exit(0);
            for ($i = 0; $i < count($rowdata['item']); $i++) {
                $len = stripos($rowdata['item'][$i], '(') == 0 ? 10 : stripos($rowdata['item'][$i], '(');
                $rowdata['item'][$i] = substr($rowdata['item'][$i], 0, $len);
                
             	if(NULL == $this->type_object[$rowdata['item'][$i]])
                {
                	echo " failed object id ".$rowdata['item'][$i].", plz input again";
                	return;
                }
                if (!is_numeric($rowdata['amount'][$i])) {
                	echo " failed amount ".$rowdata['amount'][$i].", plz input again";
                	return;
                }
                if(0 >= $rowdata['amount'][$i])
                {
                	echo " failed amount ".$rowdata['amount'][$i].", plz input again";
                	return;
                }
            }
            //print_r($rowdata);
            $strparam = "";
            $i = 0;
            while ((!empty($rowdata["item"][$i])) && (!empty($rowdata["amount"][$i]))) {
                $strparam .= "item$i=" . $rowdata['item'][$i] 
                			."&amount$i=" . $rowdata['amount'][$i] 
                			."&equiplv$i=" . $rowdata['equiplevel'][$i]
                			."&";
                $i++;
            }
            $host = $rowdata['area_host'];
            
            $itemArray = $rowdata['item'];
            $amountArray = $rowdata['amount'];
            //unset($rowdata['item'], $rowdata['amount'], $rowdata['area_host']);
            
            //exit($host . array_to_stringparam($rowdata) . $strparam . "action=15");
            $roleNames = $rowdata['reciver_name'];	//玩家名字集
			$roleIds = $rowdata['reciver_id'];		//玩家id集
			
            $successRole = array();	//成功的名单
            $failRole = array();	//失败的名单 
            $sendData = array();
            	
            //填充基本信息
            $sendData['mail_title'] = $rowdata['mail_title'];
            //$sendData['keep_time'] = $rowdata['keep_time'];
            $sendData['keep_time'] = -1; //由游戏服来修改时间
            $sendData['mail_content'] = $rowdata['mail_content'];
            $sendData['insert_time'] = date('Y-m-d H:i:s', time());
            $sendData['type'] = 0;	//0表示单发邮件
            
            $sendData['itemid1'] = $rowdata['item'][0].",".$rowdata['amount'][0].",".$rowdata['equiplevel'][0] ;
            $sendData['itemid2'] = $rowdata['item'][1].",".$rowdata['amount'][1].",".$rowdata['equiplevel'][1] ;
            $sendData['itemid3'] = $rowdata['item'][2].",".$rowdata['amount'][2].",".$rowdata['equiplevel'][2] ;
            $sendData['itemid4'] = $rowdata['item'][3].",".$rowdata['amount'][3].",".$rowdata['equiplevel'][3] ;
            
            $sendData['reason'] = $rowdata['reason'];
            $sendData['platform'] = $rowdata['platform'];
		            	
            foreach ($roleNames as $key => $value)
            {				
            	$sendData['reciver_name'] = $value;
            	$sendData['receiver_id'] = $roleIds[$key];
            	
            	//print_r($sendData);
            	$strUrl = $host . array_to_stringparam($sendData) . $strparam . "action=15";
				//print_r($strUrl);
				//exit(0);
	            $strResult = vpost($strUrl);
	            //echo " strresult = $strResult url=$st rUrl ";
	            
	            /*
	             * enum eMail_sendState
					{
						eEmail_unknowError=0,	//未知错误
						eEmail_success,	//发送成功
						eEmail_playerNotFind,	//角色名找不到
						eEmail_itemNotFind,	//附件名字写错了	
						eEmail_offlineSend,	//离线发送
					};
	             */
	            //success
	            if (0 == $strResult) {
	            	//fail
	            	$failRole[] = " unknow error rolename:".$value." roleid:$roleIds[$key] ";
	            	
	            }else if( 1 == $strResult)	
	            {
	            	$successRole[] = $value;
	            	$sendData['area_host'] = $host;
	            	//发件人
	            	$sendData['sendmanager'] = $this->auth->fields['username'];
	            	$this->db->insert("mail_message", $sendData);
	            	
	            	//记下日志
	            	insert_log(translate('MENU_MAIL_SINGLEMAIL'),translate('ADD'),$sendData);
	            	
	            	unset($sendData['area_host']);
	            }else if( 2 == $strResult)	
	            {
	            	//fail
	            	$failRole[] = " player not find rolename:".$value." ";
	            }else if( 3 == $strResult)
	            {
	            	//fail
	            	$failRole[] = " object error rolename:".$value." ";
	            }else if( 4 == $strResult)
	            {
	            	$successRole[] = "send offline mail".$value;
	            	$sendData['area_host'] = $host;
	            	//发件人
	            	$sendData['sendmanager'] = $this->auth->fields['username'];
	            	$this->db->insert("mail_message", $sendData);
	            	
	            	insert_log(translate('MENU_MAIL_SINGLEMAIL'),translate('ADD'),$sendData);
	            }
            }
            
            if(0 < count($successRole))
            {
	            echo " Success: ";
	            foreach ($successRole as $value)
	            {
	            	echo " $value ";
	            }
	            cp_tips("success");
            }
            if(0 < count($failRole))
            {
	         	echo " Fail: ";
	            foreach ($failRole as $value)
	            {
	            	echo " $value ";
	            }
	            cp_tips("error");
            }
            unset($rowdata, $itemArray, $amountArray);
            //success(translate('C_TIPS_SUCCESS_TEXT'));
            //cp_tips($resultstring == 0 ? "success" : "error");
        }else 
        {
			$arealist = get_area_list_detal();
			$data = array();
			foreach ($arealist as $key=>$value)
			{
				$data[$value['host']]=$value['id']."-".$value['name'];
			}
			
	        $this->view->assign("arealist", $this->form->select("row[area_host]", $data, '', array('id' => 'area_host')));
	        $this->view->assign("platformlist", $this->form->select("row[platform]", $this->platformlist, '', array('id' => 'platform')));
	        $this->view->assign("keeptime",$this->keeptimelist);
	        $this->view->display("mail/singlemail/add");
        }
    }

}

?>